package com.gzhryc.shared_device.oem.h5.mng.controllers.bxscn;

import com.gzhryc.common.StringTools;
import com.gzhryc.common.data.dto.AjaxResult;
import com.gzhryc.common.data.dto.ListResult;
import com.gzhryc.common.data.dto.SelectResult;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.servlet.DtoConstants;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.bxscn.code.dao.db.BXSCNOrder;
import com.gzhryc.shared_device.bxscn.code.dao.db.BXSCNShopOrder;
import com.gzhryc.shared_device.bxscn.code.dao.db.PortableEnergyBattery;
import com.gzhryc.shared_device.bxscn.code.dao.enums.PortableEnergyBatteryEnum;
import com.gzhryc.shared_device.bxscn.code.services.BXSCNOrderService;
import com.gzhryc.shared_device.bxscn.code.services.BXSCNShopOrderService;
import com.gzhryc.shared_device.bxscn.code.services.PortableEnergyBatteryService;
import com.gzhryc.shared_device.bxscn.code.services.dto.BXSCNOrderSearch;
import com.gzhryc.shared_device.bxscn.code.services.dto.BXSCNShopOrderSearch;
import com.gzhryc.shared_device.bxscn.code.services.dto.PortableEnergyBatterySearch;
import com.gzhryc.shared_device.oem.code.agent.dao.db.Agent;
import com.gzhryc.shared_device.oem.code.agent.services.AgentService;
import com.gzhryc.shared_device.oem.code.place.dao.db.PlacePhysicalStore;
import com.gzhryc.shared_device.oem.code.place.services.PlacePhysicalStoreService;
import com.gzhryc.shared_device.oem.code.place.services.dto.PlacePhysicalStoreSearch;
import com.gzhryc.shared_device.oem.h5.mng.WebConstants;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

public class PortableEnergyBatteryController {

    @Route("/bxscn/device/portable_battery/list.html")
    public String list(HttpServletRequest request) {
        request.setAttribute("stateList", PortableEnergyBatteryEnum.State.values());
        request.setAttribute("leaseTypeList", PortableEnergyBatteryEnum.LeaseType.values());
        return "/bxscn/device/portable_battery/list.html";
    }

    @Route(value = "/bxscn/device/portable_battery/list.data")
    public ListResult<PortableEnergyBattery> listData(HttpServletRequest request) {
        ListResult<PortableEnergyBattery> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
        PortableEnergyBatterySearch search = WebUtils.getParameter(request, PortableEnergyBatterySearch.class);
        Integer pageNo = WebUtils.getInteger(request, "page", 1);
        Integer pageLimit = WebUtils.getInteger(request, "limit", WebConstants.PAGE_LIMIT);

        result.getBody().setTotal(PortableEnergyBatteryService.self().countJoinBySearch(search));
        List<PortableEnergyBattery> portableEnergyBatteryList = PortableEnergyBatteryService.self().findJoinBySearch(search, pageNo, pageLimit);
        if (portableEnergyBatteryList != null && portableEnergyBatteryList.size() > 0) {
            result.setCode(DtoConstants.SUCCESS, null);
            result.getBody().setData(portableEnergyBatteryList);
        }
        return result;
    }

    @Route("/bxscn/device/portable_battery/add.html")
    public String add(HttpServletRequest request) {
        request.setAttribute("leaseTypeList", PortableEnergyBatteryEnum.LeaseType.values());
        request.setAttribute("versionNumber","1.0.0");
        return "/bxscn/device/portable_battery/edit.html";
    }

    @Route(value = {"/bxscn/device/portable_battery/add.do"})
    public AjaxResult doAdd(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "新增便携式储能电池失败");
        PortableEnergyBattery portableEnergyBattery = WebUtils.getParameter(request, PortableEnergyBattery.class);
        try {
            if (PortableEnergyBatteryService.self().add(portableEnergyBattery)) {
                result.setCode(DtoConstants.SUCCESS, null);
            }
        } catch (LogicException e) {
            result.setMsg(e.getMessage());
        }
        return result;
    }

    @Route("/bxscn/device/portable_battery/info.html")
    public String info(HttpServletRequest request) {
        String deviceSn = WebUtils.getString(request,"deviceSn");
        PortableEnergyBattery portableBattery = PortableEnergyBatteryService.self().getJoinByDeviceSn(deviceSn);
        WebUtils.setAttribute(request,portableBattery);
        return "/bxscn/device/portable_battery/info.html";
    }

    @Route(value = "/bxscn/device/portable_battery/order/list.data")
    public ListResult<BXSCNOrder> orderListData(HttpServletRequest request) {
        ListResult<BXSCNOrder> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
        BXSCNOrderSearch search = WebUtils.getParameter(request, BXSCNOrderSearch.class);
        if(StringTools.isNotBlank(search.getPortableBatterySn())) {
            Integer pageNo = WebUtils.getInteger(request, "page", 1);
            Integer pageLimit = WebUtils.getInteger(request, "limit", WebConstants.PAGE_LIMIT);

            result.getBody().setTotal(BXSCNOrderService.self(new Date()).countBySearch(search));
            List<BXSCNOrder> orderList = BXSCNOrderService.self(new Date()).findBySearch(search, pageNo, pageLimit);
            if (orderList != null && orderList.size() > 0) {
                result.setCode(DtoConstants.SUCCESS, null);
                result.getBody().setData(orderList);
            }
        }
        return result;
    }
    
    @Route(value = "/bxscn/device/portable_battery/shop_order/list.data")
    public ListResult<BXSCNShopOrder> shopOrderListData(HttpServletRequest request) {
        ListResult<BXSCNShopOrder> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
        BXSCNShopOrderSearch search = WebUtils.getParameter(request, BXSCNShopOrderSearch.class);
        if(StringTools.isNotBlank(search.getPortableBatterySn())) {
            Integer pageNo = WebUtils.getInteger(request, "page", 1);
            Integer pageLimit = WebUtils.getInteger(request, "limit", WebConstants.PAGE_LIMIT);

            result.getBody().setTotal(BXSCNShopOrderService.self(new Date()).countBySearch(search));
            List<BXSCNShopOrder> orderList = BXSCNShopOrderService.self(new Date()).findBySearch(search, pageNo, pageLimit);
            if (orderList != null && orderList.size() > 0) {
                result.setCode(DtoConstants.SUCCESS, null);
                result.getBody().setData(orderList);
            }
        }
        return result;
    }

    @Route(value = {"/bxscn/device/portable_battery/del.do"})
    public AjaxResult doDel(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "删除便携式储能电池失败");
        String deviceSn = WebUtils.getString(request,"deviceSn");
        try {
            if (PortableEnergyBatteryService.self().deleteByDeviceSn(deviceSn)) {
                result.setCode(DtoConstants.SUCCESS, null);
            }
        } catch (LogicException e) {
            result.setMsg(e.getMessage());
        }
        return result;
    }

    @Route("/bxscn/device/portable_battery/place/allocation.html")
    public String allocationPlace(HttpServletRequest request) {
        return "/bxscn/device/portable_battery/allocation_place.html";
    }

    @Route(value = {"/bxscn/device/portable_battery/place/allocation.do"})
    public AjaxResult doAllocationPlace(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "分配便携式储能电池到网点失败");
        String deviceSn = WebUtils.getString(request,"deviceSn");
        Long placeId = WebUtils.getLong(request,"placeId");
        String bindNote = WebUtils.getString(request,"bindNote");
        try {
            PlacePhysicalStore physicalStore = PlacePhysicalStoreService.self().getById(placeId);
            if(physicalStore != null) {
                PortableEnergyBattery portableEnergyBattery = PortableEnergyBatteryService.self().getByDeviceSn(deviceSn);
                if(portableEnergyBattery != null) {
                    if (PortableEnergyBatteryService.self().deploy(portableEnergyBattery,physicalStore,bindNote
                    		,PlacePhysicalStoreService.self())) {
                        result.setCode(DtoConstants.SUCCESS, null);
                    }
                }else{
                    result.setMsg("电池不存在");
                }
            }else{
                result.setMsg("网点不存在");
            }
        } catch (LogicException e) {
            result.setMsg(e.getMessage());
        }
        return result;
    }
    
    @Route("/bxscn/device/portable_battery/state/update.html")
    public String updateState(HttpServletRequest request) {
    	String deviceSn = WebUtils.getString(request,"deviceSn");
    	PortableEnergyBattery portableEnergyBattery = PortableEnergyBatteryService.self().getByDeviceSn(deviceSn);
        if(portableEnergyBattery != null) {
        	WebUtils.setAttribute(request, portableEnergyBattery);
        	if(StringTools.isNotBlank(portableEnergyBattery.getCurrentTradeNo())) {
        		BXSCNShopOrder order = BXSCNShopOrderService.self(portableEnergyBattery.getLastLeaseDate())
        				.getByTradeNo(portableEnergyBattery.getCurrentTradeNo());
        		request.setAttribute("order", order);
        	}
        }
    	request.setAttribute("stateList", PortableEnergyBatteryEnum.State.values());
        return "/bxscn/device/portable_battery/state.html";
    }

    @Route(value = {"/bxscn/device/portable_battery/state/update.do"})
    public AjaxResult doUpdateState(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "修改状态失败");
        String deviceSn = WebUtils.getString(request,"deviceSn");
        Integer state = WebUtils.getInteger(request,"state");
        if(StringTools.isNotBlank(deviceSn) && state != null) {
            PortableEnergyBattery portableEnergyBattery = PortableEnergyBatteryService.self().getByDeviceSn(deviceSn);
            if(portableEnergyBattery != null) {
            	if(portableEnergyBattery.getState().equals(state)) {
            		result.setCode(DtoConstants.SUCCESS, null);
            	}else {
            		if (PortableEnergyBatteryService.self().updateState(deviceSn,state)) {
	                    result.setCode(DtoConstants.SUCCESS, null);
	                }
            	}
            }else{
                result.setMsg("电池不存在");
            }
        }
        return result;
    }

    @Route(value = {"/bxscn/device/portable_battery/lease_type/change.do"})
    public AjaxResult doChangeLeaseType(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "切换租借方式失败");
        String deviceSn = WebUtils.getString(request, "deviceSn");
        try {
            if (PortableEnergyBatteryService.self().changeLeaseType(deviceSn)) {
                result.setCode(DtoConstants.SUCCESS, null);
            }
        } catch (LogicException e) {
            result.setMsg(e.getMessage());
        }
        return result;
    }

    @Route("/bxscn/device/portable_battery/belong.html")
    public String belong(HttpServletRequest request) {
        return "/bxscn/device/portable_battery/belong.html";
    }

    @Route(value = {"/bxscn/device/portable_battery/belong.do"})
    public AjaxResult doBelong(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "分配便携式储能电池到代理失败");
        String deviceSn = WebUtils.getString(request,"deviceSn");
        Long userId = WebUtils.getLong(request,"userId");
        try {
            Agent agent = AgentService.self().getByUserId(userId);
            if(agent == null){
                result.setMsg("非代理用户");
                return result;
            }
            if (PortableEnergyBatteryService.self().belongUser(deviceSn,userId)) {
                result.setCode(DtoConstants.SUCCESS, null);
            }
        } catch (LogicException e) {
            result.setMsg(e.getMessage());
        }
        return result;
    }

    @Route(value = {"/bxscn/device/portable_battery/undeploy.do"})
    public AjaxResult doUndeploy(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "移除分配失败，请稍后再试");
        String deviceSn = WebUtils.getString(request,"deviceSn");
        PortableEnergyBattery portableEnergyBattery = PortableEnergyBatteryService.self().getByDeviceSn(deviceSn);
        if(portableEnergyBattery != null) {
            try {
                if (PortableEnergyBatteryService.self().undeploy(portableEnergyBattery)) {
                    result.setCode(DtoConstants.SUCCESS, null);
                }
            } catch (LogicException e) {
                result.setMsg(e.getMessage());
            }
        }else {
            result.setMsg("未找到电池信息");
        }
        return result;
    }

    @Route("/bxscn/device/portable_battery/place/select.data")
    public SelectResult selectData(HttpServletRequest request) {
        SelectResult result = new SelectResult(DtoConstants.SUCCESS);
        String term = request.getParameter("term");
        Integer page = WebUtils.getInteger(request, "page", 1);

        PlacePhysicalStoreSearch search = new PlacePhysicalStoreSearch();
        search.setName(term);
        Long total = 0L;
        List<PlacePhysicalStore> list = PlacePhysicalStoreService.self()
                .findJoinBySearch(search, page, WebConstants.PAGE_LIMIT);
        if (list != null) {
            for (PlacePhysicalStore placePhysicalStore : list) {
                SelectResult.Item item = new SelectResult.Item();
                item.setId(placePhysicalStore.getId().toString());
                item.setText(placePhysicalStore.getName());
                result.getBody().getData().add(item);
            }
            total += list.size();
        }
        result.getBody().setPage(page);
        result.getBody().setLimit(WebConstants.PAGE_LIMIT);
        result.getBody().setTotal(total);
        return result;
    }
}
